import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { LocalStorage } from '@core/local.storage';
import { _HttpClient } from '@delon/theme';
import { TreeTools } from '@core/treeTools.tool';
import { environment } from '../../../../environments/environment';
import { forkJoin } from 'rxjs';

@Component({
    selector: 'app-equipmentmodal',
    templateUrl: './equipmentmodal.component.html',
    styleUrls: ['./workAreaWeave.component.less']
})
export class EquipmentModalComponent implements OnInit {
    @Input() apiUrl: any;
    @Input() operaType: any;
    @Input() width: any;
    @Input() responseData: any;
    @Input() groupDevData: any;
    @Input() popTitle: any;
    @Output() public closeModal = new EventEmitter();
    @Output() public reloadData = new EventEmitter();

    Visible = false;
    operaData: any = {};
    objData: any = {};
    thisData: any = { 'count': 0, 'vcId': [] };
    treeNodeStyle = { 'max-height': '300px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };

    equipmentinfoIndex = 1;
    emptydata: any = [{ 'id': '0' }];
    equipmentlist1: any = [];
    equipmentlist2: any = [];
    equipmentlist3: any = [];
    equipmentlist4: any = [];
    groupDevNames: any = [];
    devinfoIndex = 0;
    chooselist: any = [];
    choosegroup: any = [];

    constructor(
        public ls: LocalStorage,
        public treeTools: TreeTools,
        private http: _HttpClient
    ) { }

    ngOnInit() {
        setTimeout(() => {
            this.Visible = true;
            let devids = '';
            let devGroupIds = '';
            devids = this.responseData.vcDevid ? this.responseData.vcDevid : '';
            devGroupIds = this.responseData.vcDevgroupid ? this.responseData.vcDevgroupid : '';
            const updateApi = [
                this.http.get(environment.devscore + '/sys/systdevorg/getStaDevs?staid=' + this.responseData.vcStaId + '&devids=' + devids + '&devtype=' + this.responseData.devtype),
                this.http.get(environment.devscore + '/sys/systdevorg/getStadevGroup?staid=' + this.responseData.vcStaId + '&devGroupIds=' + devGroupIds)
            ];
            forkJoin(updateApi).subscribe((results: any) => {
                if (!results[0].code) {
                    for (const item of results[0].data) {
                        switch (Number(item.opClass) % 2) {
                            case 0:
                                this.equipmentlist1.push({
                                    'opValue': item.opValue,
                                    'opName': item.opName,
                                    'opCheck': this.oldvalue(item.opCheck, 'single'),
                                    'opClass': item.opClass
                                });
                                break;
                            case 1:
                                this.equipmentlist2.push({
                                    'opValue': item.opValue,
                                    'opName': item.opName,
                                    'opCheck': this.oldvalue(item.opCheck, 'single'),
                                    'opClass': item.opClass
                                });
                                break;
                            case NaN:
                                this.equipmentlist3.push({
                                    'opValue': item.opValue,
                                    'opName': item.opName,
                                    'opCheck': this.oldvalue(item.opCheck, 'single'),
                                    'opClass': item.opClass
                                });
                                break;
                        }
                    }
                    if (this.chooselist[this.devinfoIndex]) {
                        for (let i = 0; i < this.chooselist[this.devinfoIndex]; i++) {
                            for (const item of this.equipmentlist1) {
                                if (this.chooselist[this.devinfoIndex][i] === item.opValue) {
                                    item.opCheck = true;
                                    break;
                                }
                            }
                            for (const item of this.equipmentlist2) {
                                if (this.chooselist[this.devinfoIndex][i] === item.opValue) {
                                    item.opCheck = true;
                                    break;
                                }
                            }
                            for (const item of this.equipmentlist3) {
                                if (this.chooselist[this.devinfoIndex][i] === item.opValue) {
                                    item.opCheck = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                if (!results[1].code) {
                    for (const item of results[1].data) {
                        this.equipmentlist4.push({
                            'groupname': item.groupname,
                            'opCheck': this.oldvalue(item.check, 'group'),
                            'devids': item.devids,
                            'groupid': item.groupid,
                            'devnames': item.devnames
                        });
                    }
                    if (this.choosegroup[this.devinfoIndex]) {
                        for (let i = 0; i < this.choosegroup[this.devinfoIndex]; i++) {
                            for (const node of this.equipmentlist4) {
                                if (this.choosegroup[this.devinfoIndex][i] === node.groupid) {
                                    node.opCheck = true;
                                    break;
                                }
                            }
                        }
                    }
                    // 还原子设备信息 
                    for (const item of this.equipmentlist4) {
                        if (item.opCheck) {
                            for (let i = 0; i < item.devnames.split(',').length; i++) {
                                this.groupDevNames.push({
                                    opCheck: this.formatCheck(item.devids.split(',')[i]),
                                    devname: item.devnames.split(',')[i],
                                    devids: item.devids.split(',')[i]
                                })
                            }
                        }
                    }
                }
            });
        }, 200);
    }
    formatCheck(data) {
        let status = false;
        for (const item of this.groupDevData.split(',')) {
            if (data === item) {
                status = true;
            }
        }
        return status;
    }
    groupDevNamesChange(data) {
        this.groupDevNames = [];
        if (data.opCheck) {
            setTimeout(() => {
                for (let i = 0; i < data.devnames.split(',').length; i++) {
                    this.groupDevNames.push({
                        opCheck: true,
                        devname: data.devnames.split(',')[i],
                        devids: data.devids.split(',')[i]
                    })
                }
            }, 200);
        }
    }
    repeat(data) {
        const temparr = [];
        let string = '';

        for (const item of data) {
            if (temparr.indexOf(item) === -1 && item !== '') {
                temparr.push(item);
            }
        }
        for (const item of temparr) {
            string += ',' + item;
        }
        string = string.replace(',', '');
        return string;
    }

    duplicate(data) {
        const temparr = [];
        let string = '';

        for (const item of data.split(',')) {
            if (temparr.indexOf(item) === -1 && item !== '') {
                temparr.push(item);
            }
        }
        for (const item of temparr) {
            string += ',' + item;
        }
        string = string.replace(',', '');
        return string;
    }

    formatData(data) {
        if (!data) {
            data = '';
        }
        return data;
    }

    oldvalue(check, type) {
        switch (type) {
            case 'single':
                if (!this.chooselist[this.devinfoIndex] && !this.choosegroup[this.devinfoIndex]) {
                    if (check === 'checked') {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            case 'group':
                if (!this.choosegroup[this.devinfoIndex] && !this.chooselist[this.devinfoIndex]) {
                    if (check === 'checked') {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
        }
    }

    // 设备弹出层（全选/清空/返回）
    checkeqlist(index, operation) {
        const array = [0, this.equipmentlist1, this.equipmentlist2, this.equipmentlist3, this.equipmentlist4];
        switch (operation) {
            case 'all':
                for (const item of array[index]) {
                    item.opCheck = true;
                }
                break;
            case 'clear':
                for (const item of array[index]) {
                    item.opCheck = false;
                }
                break;
            case 'unall':
                for (const item of array[index]) {
                    item.opCheck = !item.opCheck;
                }
                break;
        }
    }

    Ok() {
        let devName = '';
        let devId = '';
        let groupName = '';
        let groupId = '';
        let groupDevName = '';
        let groupDevId = '';
        const array = [this.equipmentlist1, this.equipmentlist2, this.equipmentlist3];

        // 设备信息和ID
        for (const item of array) {
            for (const list of item) {
                if (list.opCheck) {
                    list.opName ? devName += ',' + list.opName : devName += '';
                    list.opValue ? devId += ',' + list.opValue : devId += ',';
                }
            }
        }
        devName = this.duplicate(devName);
        devId = this.duplicate(devId);
        // 设备分组和ID
        for (const item of this.equipmentlist4) {
            if (item.opCheck) {
                item.groupname ? groupName += ',' + item.groupname : groupName += '';
                item.groupid ? groupId += ',' + item.groupid : groupId += '';
            }
        }
        for (const item of this.groupDevNames) {
            if (item.opCheck) {
                item.devname ? groupDevName += ',' + item.devname : groupDevName += '';
                item.devids ? groupDevId += ',' + item.devids : groupDevId += '';
            }
        }
        groupName = this.duplicate(groupName);
        groupId = this.duplicate(groupId);
        groupDevName = this.duplicate(groupDevName);
        groupDevId = this.duplicate(groupDevId);
        this.reloadData.emit(devName + '|' + devId + '++' + groupName + '|' + groupId + '|' + groupDevName + '|' + groupDevId);
        this.Cancel();
    }
    Cancel() {
        this.Visible = false;
        setTimeout(() => {
            this.closeModal.emit();
        }, 200);
    }
}
